package com.youdelu.basicframe.base.data;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.collection.LruCache;

import com.youdelu.basicframe.base.config.Constants;

import javax.inject.Inject;
import javax.inject.Singleton;

import dagger.Lazy;
import dagger.hilt.internal.Preconditions;
import retrofit2.Retrofit;

/**
 * 统一管理数据业务层
 * @author youdelu
 */
@Singleton
public class DataRepository implements  IDataRepository {

    @Inject
    Lazy<Retrofit> mRetrofit;

    @Inject
    Application mApplication;

    /**
     * 缓存 Retrofit Service
     */
    private LruCache<String,Object> mRetrofitServiceCache;

    @Inject
    public DataRepository(){
    }

    /**
     * 提供上下文{@link Context}
     * @return {@link #mApplication}
     */
    @Override
    public Context getContext() {
        return mApplication;
    }

    /**
     * 传入Class 通过{@link Retrofit#create(Class)} 获得对应的Class
     * @param service
     * @param <T>
     * @return {@link Retrofit#create(Class)}
     */
    @Override
    public <T> T getRetrofitService(@NonNull Class<T> service) {
        if(mRetrofitServiceCache == null){
            mRetrofitServiceCache = new LruCache<>(Constants.DEFAULT_RETROFIT_SERVICE_MAX_SIZE);
        }
        Preconditions.checkNotNull(mRetrofitServiceCache);

        T retrofitService = (T)mRetrofitServiceCache.get(service.getCanonicalName());
        if(retrofitService == null){
            synchronized (mRetrofitServiceCache) {
                if(retrofitService == null){
                    retrofitService = mRetrofit.get().create(service);
                    //缓存
                    mRetrofitServiceCache.put(service.getCanonicalName(),retrofitService);
                }

            }
        }

        return retrofitService;
    }

}
